﻿@page "/scan"

<h4>Scan</h4>
<div class="container-fluid bg-custom my-1 pb-1">
    @switch (pageState)
    {
        case PageState.Options:
            <div class="run-box bg-custom">
                <div class="form-inline">
                    <label class="mr-2" for="RunId">Run ID:</label>
                    <input type="text" class="form-control mr-2" id="RunId" placeholder="Enter Run ID" @bind="RunIdInput" />
                    <div class="form-check mr-2">
                        <input type="checkbox" class="form-check-input" id="UseTimestampCheckbox" @bind="UseTimestamp" />
                        <label class="form-check-label" for="UseTimestampCheckbox">Use Timestamp</label>
                    </div>
                    <button class="btn btn-primary" @onclick="BeginScan">Start Scan</button>
                </div>
            </div>
            <CollectorOptionsRazor />
            break;
        case PageState.Scanning:
            <Scanning />
            break;
        case PageState.Finished:
            <p>Scanning complete.</p>
            <button class="btn btn-primary" @onclick="GoToOptions">Scan Again</button>
            break;
        case PageState.Error:
            <p>An Error Occured while collecting.</p>
            break;
    }
</div>

@code {
    enum PageState
    {
        Options,
        Scanning,
        Finished,
        Error
    }
    bool UseTimestamp = true;
    string RunIdInput = "";

    PageState pageState = PageState.Options;

    System.Threading.Timer timer;

    async void BeginScan()
    {
        appData.RunId = UseTimestamp ? DateTime.Now.ToString() : RunIdInput;
        timer = new System.Threading.Timer((_) => InvokeAsync(() => StateHasChanged()), null, 0, 100);
        appData.CollectOptions.RunId = appData.FirstRunId;
        pageState = PageState.Scanning;
        this.StateHasChanged();
        if (await Task.Factory.StartNew(() => AttackSurfaceAnalyzerClient.RunCollectCommand(appData.CollectOptions)) == Microsoft.CST.AttackSurfaceAnalyzer.Types.ASA_ERROR.NONE)
        {
            pageState = PageState.Finished;
        }
        else
        {
            pageState = PageState.Error;
        }
        AttackSurfaceAnalyzerClient.ClearCollectors();
    }

    void GoToOptions()
    {
        pageState = PageState.Options;
    }
}
